<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="模板CODE"
              style="margin-right: -35px"
            >
              <a-input
                :disabled="disable"
                placeholder="请输入模板编码"
                v-decorator="['templateCode', validatorRules.templateCode ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="模板类型">
              <j-dict-select-tag  @change="handleChangeTemplateType" :triggerChange="true" dictCode="msgType" v-decorator="['templateType', validatorRules.templateType ]" placeholder="请选择模板类型">
              </j-dict-select-tag>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24" >
          <a-col :span="24" pull="2">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="模板标题"
              style="margin-left: -15px">
              <a-input
                placeholder="请输入模板标题"
                v-decorator="['templateName', validatorRules.templateName]"
                style="width: 122%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24" >
          <a-col :span="24" pull="2">
            <a-form-item
              v-show="useEditor2" 
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="小程序appId"
              style="margin-left: 15px">
              <a-input 
                placeholder="请输入小程序appId"
                v-decorator="['appId', validatorRules.appId]"
                style="width: 122%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24" >
          <a-col :span="24" pull="2">
            <a-form-item
              v-show="useEditor2" 
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="小程序跳转链接"
              style="margin-left: 20px">
              <a-input 
                placeholder="请输入小程序跳转链接"
                v-decorator="['path', validatorRules.path]"
                style="width: 122%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <div v-for="(item, index) in fileds" :key="index">
            <a-form-item label="字段名称" class="slef-item" >
              <a-input
                v-decorator="[
                  `names[${index}][key]`,
                  {
                    initialValue: item['key'],
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入字段名称'
                      }
                    ]
                  }
                ]"
              ></a-input>
            </a-form-item>
            <div class="name-icon">
              <a-form-item  label="字段变量" class="slef-item">
                <a-input 
                  v-decorator="[
                    `names[${index}][value]`,
                    {
                      initialValue: item['value'],
                      validateTrigger: ['change', 'blur'],
                      rules: [
                        {
                          required: true,
                          whitespace: true,
                          message: '请输入字段变量'
                        }
                      ]
                    }
                  ]"
                ></a-input>
                <a-icon class="dynamic-delete-button mt-10" type="minus-circle-o" @click="() => remove(index)" />
              </a-form-item>
              
          </div>
        </div>
        <a-row :gutter="24">
          <a-col :span="14" :offset="14" class="info-action">
            <a-button v-show="useEditor2" type="link" @click="addfileds"> <a-icon type="plus" /> 添加消息模板字段 </a-button>
            <span type="link" @click="prevImage(insurl)" v-show="useEditor2" class="icon-info"
                  ><a-icon type="question-circle" style="margin-right:8px" />操作说明</span
                >
          </a-col>
        </a-row>

        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="4">
            <a-form-item
              v-show="!useEditor && !useEditor2"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="模板内容"
              style="margin-left: 4px;width: 126%">
              <a-textarea placeholder="请输入模板内容" v-decorator="['templateContent', validatorRules.templateContent ]" :autosize="{ minRows: 8, maxRows: 8 }"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :span="24" pull="4">
            <a-form-item
              v-show="useEditor"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="模板内容"
              style="margin-left: 4px;width: 126%">
              <j-editor  v-model="templateEditorContent"></j-editor>
            </a-form-item>
          </a-col>
        </a-row>
        <a-modal v-model="visible2" title="查看图片" @ok="visible2 = false" :footer="null" width="60%" :mask="true">
        <div class="previmg">
          <img :src="prevImageUrl" style="maxWidth:80%" />
        </div>
       </a-modal>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import {httpAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import { duplicateCheck } from '@/api/api'
  import JEditor from '@/components/jeecg/JEditor'

  export default {
    name: "SysMessageTemplateModal",
    components:{
      JEditor
    },
    data() {
      return {
        title: "操作",
        visible: false,
        disable: true,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
        templateCode: {rules: [{required: true, message: '请输入模板CODE!' },{validator: this.validateTemplateCode}]},
        templateName: {rules: [{required: true, message: '请输入模板标题!'}]},
        templateContent: {rules: []},
        templateType: {rules: [{required: true, message: '请输入模板类型!'}]},
        appId: {rules: [{required: true, message: '请输入小程序appId!'}]},
        path: {rules: [{required: false}]},
        },
        url: {
          add: "/sys/message/sysMessageTemplate/add",
          edit: "/sys/message/sysMessageTemplate/edit",
        },
        useEditor:false,
        useEditor2:false,
        templateEditorContent:"",
        fileds: [],
        insurl: 'https://img.bzhz.jnbygroup.com/modalimg.png',
        prevImageUrl:'',
        visible2:false
      }
    },
    created() {
    },
    methods: {
      add() {
        this.disable = false;
        this.edit({});
      },
      addfileds() {
        const obj = { lable: '', val: '' }
        let { fileds } = this
        fileds.push(obj)
        this.fileds = fileds
      },
      remove(index) {
        let { fileds } = this
        fileds.splice(index, 1)
        this.fileds = fileds
      },
      edit(record) {
        console.log(record)
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.useEditor = (record.templateType==2 || record.templateType==4)
        this.useEditor2 = (record.templateType==3)
        if(this.useEditor){
          this.templateEditorContent=record.templateContent
        }else{
          this.templateEditorContent=''
        }
        if(this.useEditor2){
         
          var arr = JSON.parse(record.templateContent);
          var obj = {};
          var arr2 = [];
          console.log(arr)
          for(var i=0;i<arr.length;i++){
           arr2 = arr.filter(item => item.key != 'appId' &&  item.key != 'path')
            
            if(arr[i].key == 'appId'){
              this.model.appId = arr[i].value

            }
            if(arr[i].key == 'path'){
              this.model.path = arr[i].value
     
            }
            
            }
            
            console.log(arr2)
            this.fileds = arr2
          }
     
        
      
        this.visible = true;
        this.$nextTick(() => {
          console.log(this.model)
          if(this.useEditor2){

             this.form.setFieldsValue(pick(this.model, 'templateCode', 'templateName','templateContent', 'templateTestJson','path','appId', 'templateType'))
          }
          if(this.useEditor){
            this.form.setFieldsValue(pick(this.model, 'templateCode', 'templateName', 'templateTestJson', 'templateType'))
          }else{
            this.form.setFieldsValue(pick(this.model, 'templateCode', 'templateContent', 'templateName', 'templateTestJson', 'templateType'))
          }
          
        });
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.disable = true;
        this.fileds = [];
        this.useEditor2 = false;
      },
      handleOk() {
        this.model.templateType = this.templateType;
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err || (err.appId.errors.length >0 && !this.useEditor2)) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化

            if(this.useEditor){
              formData.templateContent=this.templateEditorContent
            }
            console.log(formData)
            if(this.useEditor2){
              if(formData.names.length > 0){
                var obj = {};
                var arr = [];
                if(formData.appId){
                  formData.names.push({
                    'key':'appId',
                    'value':formData.appId
                  })
                }
                if(formData.path){
                  formData.names.push({
                    'key':'path',
                    'value':formData.path
                  })
                }

                formData.templateContent =  JSON.stringify(formData.names);
 
              }
              
            
            }
          
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })


          }
        })
      },
      validateTemplateCode(rule, value, callback){
        var params = {
          tableName: "sys_sms_template",
          fieldName: "template_code",
          fieldVal: value,
          dataId: this.model.id
        }
        duplicateCheck(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback(res.message);
          }
        })

      },
      handleCancel() {
        this.close()
      },
      handleChangeTemplateType(value){
        //如果是邮件类型那么则改变模板内容是富文本编辑器
        this.useEditor = (value==2 || value==4)
        console.log(this.useEditor )
        console.log(value)
        this.useEditor2 = value == 3
      },
      prevImage(url) {
      this.prevImageUrl = url
      this.visible2 = true
      },

    }
  }
</script>

<style lang="less">
.dynamic-delete-button {
  cursor: pointer;
  position: absolute;
  right: -26px;
  top: 8px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.self-item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
  justify-content: flex-start;
}
.icon-info {
  color: orange;
  cursor: pointer;
}

.info-action {
  margin-bottom: 20px;
  justify-content: flex-start;
}
.ml-20 {
  margin-left: 20px;
}
.name-icon {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  position: relative;
}
.slef-item {
  display: flex;
  width: 94%;
}
.ant-form-item-control-wrapper{
 flex: 1;
}
.mt-10{
  margin-top: -10px;
}
.previmg {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
